package com.zkteco.fingerprint.service;

import com.zkteco.fingerprint.entity.FingerprintData;
import com.zkteco.fingerprint.repository.FingerprintDataRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

/**
 * 指纹数据管理服务
 */
@Service
@Transactional
public class FingerprintDataService {
    
    @Autowired
    private FingerprintDataRepository fingerprintRepository;
    
    /**
     * 保存指纹数据
     */
    public FingerprintData save(FingerprintData fingerprintData) {
        return fingerprintRepository.save(fingerprintData);
    }
    
    /**
     * 根据用户ID查找指纹数据
     */
    public Optional<FingerprintData> findByUserId(String userId) {
        return fingerprintRepository.findByUserId(userId);
    }
    
    /**
     * 查找所有启用的指纹数据
     */
    public List<FingerprintData> findAllActive() {
        return fingerprintRepository.findAllActive();
    }
    
    /**
     * 根据用户名查找指纹数据
     */
    public List<FingerprintData> findByUserName(String userName) {
        return fingerprintRepository.findByUserName(userName);
    }
    
    /**
     * 删除指纹数据
     */
    public void deleteByUserId(String userId) {
        fingerprintRepository.deleteByUserId(userId);
    }
    
    /**
     * 检查用户ID是否存在
     */
    public boolean existsByUserId(String userId) {
        return fingerprintRepository.existsByUserId(userId);
    }
    
    /**
     * 统计活跃指纹数量
     */
    public Long countActive() {
        return fingerprintRepository.countActive();
    }
    
    /**
     * 获取所有指纹数据
     */
    public List<FingerprintData> findAll() {
        return fingerprintRepository.findAll();
    }
    
    /**
     * 禁用指纹数据
     */
    public void disableFingerprint(String userId) {
        Optional<FingerprintData> optional = fingerprintRepository.findByUserId(userId);
        if (optional.isPresent()) {
            FingerprintData data = optional.get();
            data.setStatus(0);
            fingerprintRepository.save(data);
        }
    }
    
    /**
     * 启用指纹数据
     */
    public void enableFingerprint(String userId) {
        Optional<FingerprintData> optional = fingerprintRepository.findByUserId(userId);
        if (optional.isPresent()) {
            FingerprintData data = optional.get();
            data.setStatus(1);
            fingerprintRepository.save(data);
        }
    }
} 